package org.cweili.vehicle.service.driver

import org.cweili.vehicle.entity.Journey
import org.cweili.vehicle.entity.Vehicle
import org.cweili.vehicle.service.BaseService
import org.cweili.vehicle.util.Const
import org.cweili.vehicle.util.JSON
import org.directwebremoting.annotations.RemoteProxy
import org.directwebremoting.spring.SpringCreator
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service

/**
 * 司机工作服务
 *
 * @author Cweili
 * @version 2013年7月27日 下午11:30:28
 *
 */
@RemoteProxy(creator = SpringCreator.class)
@Service
class DriverWorkService extends BaseService {

	Page<Journey> getJourneyList(String json) {
		def obj = JSON.parseObject(json)

		def page = JSON.getInteger(obj, "page")

		return journeyRepository.findByDriverAndVerifyStatus(getCustomer(), Journey.VERIFY_PASSED,
		new PageRequest(page, Const.PAGE_SIZE, Sort.Direction.DESC, "id"))
	}

	Page<Vehicle> getVehicleList(String json) {
		def obj = JSON.parseObject(json)

		def page = JSON.getInteger(obj, "page")

		def pageable = new PageRequest(0, Integer.MAX_VALUE, Sort.Direction.DESC, "id")
		def journeyList = journeyRepository.findByDriverAndVerifyStatus(getCustomer(),
				Journey.VERIFY_PASSED, pageable).getContent()
		def vehicleSet = new HashSet<Vehicle>()
		for (journey in journeyList) {
			def vehicle = journey.getVehicle()
			if (vehicle) {
				vehicleSet.add(vehicle)
			}
		}
		def vehicleList = new ArrayList<Vehicle>(Const.PAGE_SIZE)
		def begin = page * Const.PAGE_SIZE
		def end = begin + Const.PAGE_SIZE
		def i = 0
		for (vehicle in vehicleSet) {
			if (begin <= i && end > i) {
				vehicleList.add(vehicle)
			}
			++i
		}

		return new PageImpl<Vehicle>(vehicleList, pageable, vehicleSet.size())
	}
}
